#include "ChatServer.h"
#include "../log.h"
#include "../Singleton.h"
#include "../AsioIoContextPool.h"


Server::Server(boost::asio::io_context& ioc, uint16_t port)
:_port(port)
,_ioc(ioc)
,_acceptor(_ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::any(), port))
{
    log_info("Server listening on port: {}", port);
    _StartAccept();
}

void Server::DeleteSession(const std::string& sessionId)
{
    std::lock_guard<std::mutex> lock(_sessions_lock);
    _sessions.erase(sessionId);
}


void Server::_StartAccept()
{
    auto& ioc = Singleton<AsioIoContextPool>::GetInstance()->GetIoContext();
    std::shared_ptr<Session> session = std::make_shared<Session>(ioc, this);
    _acceptor.async_accept(session->GetSocket(), [this, session](const boost::system::error_code& ec){
        _HandleAccept(session, ec);
    });
}

void Server::_HandleAccept(std::shared_ptr<Session> session, const boost::system::error_code& ec)
{
    if(!ec)
    {
        // log_info("Accepted connection from: {}", EndpointToString(session->GetSocket().remote_endpoint()));
        std::lock_guard<std::mutex> lock(_sessions_lock);
        _sessions.insert(std::make_pair(session->GetSessionId(), session));
        session->Start();
    }
    else
    {
        log_warning("Accept error: {}", ec.message());
    }

    _StartAccept(); //继续监听下一个连接
}